
package pl.genapp.stocksense.libraries;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import pl.genapp.stocksense.others.GlobalData;
import pl.genapp.stocksense.others.PostExecuteReaction;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;

public class HttpMakerAsyncTask extends AsyncTask<String, Void, String> {
	
	Context							context;
	PostExecuteReaction<JSONObject>	reaction;
	
	public HttpMakerAsyncTask(Context context, PostExecuteReaction<JSONObject> reaction) {
		this.context = context;
		this.reaction = reaction;
		
	}
	
	@Override
	protected String doInBackground(String... JsonData) {
		
		HttpClient httpClient = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost(GlobalData.HttpGateway);
		
		try {
			List<NameValuePair> data = new ArrayList<NameValuePair>(1);
			data.add(new BasicNameValuePair("data", JsonData[0]));
			
			httpPost.setEntity(new UrlEncodedFormEntity(data));
			
			HttpResponse response = httpClient.execute(httpPost);
			
			BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
			StringBuilder builder = new StringBuilder();
			for (String line = null; (line = reader.readLine()) != null;) {
				builder.append(line).append("\n");
			}
			
			Log.d("mojaapp", builder.toString());
			
			return builder.toString();
			
		} catch (ClientProtocolException e) {
			
		} catch (IOException e) {
			
		}
		
		return null;
		
	}
	
	@Override
	protected void onPostExecute(String result) {
		
		if (result != null) {
			
			try {
				JSONObject jsonObject = new JSONObject(result);
				
				if (jsonObject.getInt("success") == 1)
					reaction.onSuccess(context, jsonObject);
				else if (jsonObject.getInt("error") == 1)
					reaction.onError(context, jsonObject);
				else
					reaction.onOthers(context);
				
			} catch (JSONException e) {
				e.printStackTrace();
			}
		} else
			reaction.onOthers(context);
		
	}
	
}
